package com.hksj.jetlinks.manager;

import com.hksj.jetlinks.cache.RedisTokenStore;
import com.hksj.jetlinks.constant.AuthConstants;
import com.hksj.jetlinks.model.LoginUser;
import com.hksj.jetlinks.model.SimpleUserToken;
import com.hksj.jetlinks.service.JetUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class TokenManager {
    @Autowired
    private RedisTokenStore<ConcurrentHashMap<String,Object>> redisTokenStore;
    @Autowired
    private JetUserService jetUserService;

    public LoginUser getUserInfo(String token) {
        LoginUser loginUser = null;
        if (StringUtils.hasText(token)) {
            Map<String, Object> tokenInfoMap = redisTokenStore.getCacheMap(getTokenRedisKey(token));
            if (!ObjectUtils.isEmpty(tokenInfoMap)){
                SimpleUserToken simpleUserToken = SimpleUserToken.of(tokenInfoMap);
                loginUser = jetUserService.getLoginUserWithCache(simpleUserToken);
            }
        }
        return loginUser;
    }

    private String getTokenRedisKey(String key) {
        return AuthConstants.CACHE_KEY_THIRD_USER_TOKEN.concat(key);
    }
}
